package br.com.devmedia.conversores;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.devmedia.beans.Setor;

public class ConverterSetor implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String string) {

		if (string == null || string.equals("Selecione um Setor"))
			return null;

		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		EntityManager manager = (EntityManager) request.getAttribute("manager");

		return manager.find(Setor.class, Integer.parseInt(string));
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
		if (obj == null)
			return null;

		Setor setor = (Setor) obj;
		return setor.getId().toString();
	}

}
